use crate::{JEnv, JLocal, JObject, JRc, JVm};

pub struct JWeak<T: AsRef<JObject> + 'static> {
	inner: &'static T,
}
impl<T: AsRef<JObject> + 'static> Drop for JWeak<T> {
	fn drop(&mut self) {
		JVm::singleton(None).unwrap().env().unwrap().del_weak(self.inner.as_ref())
	}
}
impl<T: AsRef<JObject>> JWeak<T> {
	pub(crate) fn try_from(value: sys::jobject) -> Result<Self, ()> {
		if !value.is_null() {
			Ok(Self {
				inner: unsafe { &*(value as *mut T) },
			})
		} else {
			Err(())
		}
	}
}

impl<T: AsRef<JObject>> JWeak<T> {
	pub fn loacl<'a, 'b>(&'b self, env: &'a JEnv) -> Option<JLocal<'a, T>> {
		env.new_local(self.inner)
	}
	pub fn global(&self, env: &JEnv) -> Option<JRc<T>> {
		env.new_global(self.inner)
	}
}
